package com.scfire.project

import grails.converters.JSON
import grails.transaction.Transactional

import java.awt.image.BufferedImage
import java.text.DateFormat
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.List;

import javax.imageio.ImageIO

import net.sf.json.JSONArray
import net.sf.json.JSONObject

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import com.google.zxing.BarcodeFormat
import com.mongodb.BasicDBObject
import com.mongodb.DBCollection
import com.mongodb.DBObject
import com.mongodb.gridfs.GridFS
import com.mongodb.gridfs.GridFSInputFile
import com.scfire.baseInfo.Gson
import com.scfire.content.*
import com.scfire.fund.FDonate
import com.scfire.fund.FOperate
import com.scfire.fund.FRuler
import com.scfire.fund.FundPool
import com.scfire.message.SystemMessage
import com.scfire.security.Member
import com.scfire.util.*
import com.scfire.weixin.WeiXinConstants

class ProjectController {
	
	Log LOG = LogFactory.getLog(ProjectController.class)
	
	def springSecurityService
	def deviceInfoService
	def weiXinService
	def userService
	def mongo
	def grailsApplication
	
	
	
	/**
	 * 爱心池
	 * @param null
	 * @return null
	 *
	 * **/
	
	def fundPoolList() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		params.max = 20
		List<String> projectNames = new LinkedList <String>()
		def Criteria = FundPool.createCriteria()
		def CriteriaFRuler = FRuler.createCriteria()
		def filterClosure = {
			order("updateDate", "desc")
		}
		def fundPools = Criteria.list(params,filterClosure)
		def totalCount = Criteria.list(params,filterClosure).size()
		JSONArray fRulesjson = new JSONArray()
		for(FundPool f: fundPools){
			int projectSize=0;
			int totalmoney=0;
			def filterClosureFRuler = {
				eq("fundPool", f.id)
			}
			def fRulers=CriteriaFRuler.list(filterClosureFRuler)
			for(FRuler fRuler : fRulers){
				totalmoney+=fRuler.donatefund
				projectSize++
			}
				JSONObject json = new JSONObject()
				json.put("id", f.id)
				json.put("name",f.name)
				json.put("type",f.type)
				json.put("coverPic",f.coverPic)
				json.put("fullName", f.fullName)
				json.put("description", f.description)
				json.put("totaldonate", totalmoney/100)
				json.put("totalProject", projectSize)
				fRulesjson.add(json)
		}
		def url = WeiXinConstants.server + "/project/funPoolList"
		if(request.getQueryString()){
			url = (url + "?" + request.getQueryString())
		}
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.server+"/images/scfire.png"
		def shareUrl = WeiXinConstants.server
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "fundpoollist", model: [totalCount:totalCount]
				}
				if("mobile".equals(str)){
					render view: "fundpoollistmb", model: [totalCount:totalCount,user:(Member)user,
						appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign,shareUrl:shareUrl , imgUrl : imgUrl]
				}
			}
			json {
				render fRulesjson as JSON
			}
		}
		
	}
	
	/**
	 * 跳转到查询页面
	 */
	def projectsearch(){
		render view: "search", model:[]
	}
	
	def fundpooldetail(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		//def roles = springSecurityService.getAuthentication()?.authorities
		
		params.max = 20
		int total_times=0
		
		String fundPoolid = params.fundPoolid
		FundPool fundpool= null
		fundpool = FundPool.findById(Long.valueOf(fundPoolid))
		def fDonates =fundpool.fdonates
		total_times=FDonate.countByFundPool(fundpool.id)
		def filterClosure = {
			and{
				eq("fundPool",fundpool.id)
				order("createDate","desc")
				}
			}
		def Criteria = FRuler.createCriteria()
		def fRules =Criteria.list(params,filterClosure)
		def totalProject =Criteria.list(filterClosure).size()
		
		
		
		def url = WeiXinConstants.server + "/project/fundpooldetail"
		if(request.getQueryString()){
			url = (url + "?" + request.getQueryString())
		}
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.img_url
		imgUrl += fundpool.coverPic
		def shareUrl = WeiXinConstants.server
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "fundpooldetail", model: [fRules:fRules,fundpool:fundpool,total_times:total_times,totalProject:totalProject]
				}
				if("mobile".equals(str)){
					render view: "fundpooldetailmb", model: [fRules:fRules,fundpool:fundpool,total_times:total_times,totalProject:totalProject,
						appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign,shareUrl:shareUrl,imgUrl:imgUrl]
				}
			}
			json {
				JSONArray fRulesjson = new JSONArray()
				
				for(FRuler f:fRules){
					int donatessize=0
					JSONObject json = new JSONObject()
					/*for(FDonate fd: fDonates){
					if(fd.project==f.project){
						donatessize++
					}
				}*/
					def filterClosures = {
						and{
							eq("fundPool",f.fundPool.id)
							eq('project', f.project.id)
							}
						}
					def Criterias = FDonate.createCriteria()
					donatessize= Criterias.count(filterClosures)
					
					json.put("projectid", f.project.id)
					json.put("img", f.project.img)
					json.put("name", f.project.name)
					json.put("progress", f.project.progress)
					json.put("verified", f.project.verified)
					json.put("donatessize", donatessize)
					json.put("savemoney", f.donatefund/100)
					json.put("description", f.project.description)
					
					fRulesjson.add(json)
				}
				render fRulesjson as JSON
			}
		}
	}

	
	def fundpooldetailPC(){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		//def roles = springSecurityService.getAuthentication()?.authorities
		
		params.max = 20
		int total_times=0
		
		String fundPoolid = params.fundPoolid
		FundPool fundpool= null
		fundpool = FundPool.findById(Long.valueOf(fundPoolid))
		def fDonates =fundpool.fdonates
		total_times=FDonate.countByFundPool(fundpool.id)
		def filterClosure = {
			and{
				eq("fundPool",fundpool.id)
				order("createDate","desc")
				}
			}
		def Criteria = FRuler.createCriteria()
		def fRules =Criteria.list(params,filterClosure)
		def totalProject =Criteria.list(filterClosure).size()
		
		
		
		def url = WeiXinConstants.server + "/project/fundpooldetail"
		if(request.getQueryString()){
			url = (url + "?" + request.getQueryString())
		}
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.img_url
		imgUrl += fundpool.coverPic
		def shareUrl = WeiXinConstants.server
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "fundpooldetail", model: [fRules:fRules,fundpool:fundpool,total_times:total_times,totalProject:totalProject]
				}
			}
			json {
				JSONArray fRulesjson = new JSONArray()
				
				for(FRuler f:fRules){
					int donatessize=0
					JSONObject json = new JSONObject()
					def filterClosures = {
						and{
							eq("fundPool",f.fundPool)
							eq('project', f.project)
							}
						}
					def Criterias = FDonate.createCriteria()
					donatessize= Criterias.count(filterClosures)
					
					json.put("projectid", f.project.id)
					json.put("img", f.project.img)
					json.put("name", f.project.name)
					json.put("progress", f.project.progress)
					json.put("verified", f.project.verified)
					json.put("donatessize", donatessize)
					json.put("savemoney", f.donatefund/100)
					json.put("description", f.project.description)
					
					fRulesjson.add(json)
				}
				render fRulesjson as JSON
			}
		}	
	}
	
	/**
	 * 项目申请拨款或延期
	 * @param name,description,detail
	 * @return null
	 *
	 * **/
	def appliYanorFun(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd H:mm");
		def project
		def message
		def member 
		def frist=0
		Map<String, String> donateUsersOpenid = new HashMap<String, String>()
		Date  date = new Date();
		def members = Member.findAllByPushFlag(true);
		for(Member member2:members){
			donateUsersOpenid.put(member2?.openid , member2?.nickname)
		}
		try{ 
			project = Project.findById(params.Id);
			member = Member.findById(project.member)
			if(params.shenq=="1"){
				if(project?.apliNum<1){
					project.apliNum=1
					project.save(flush: true)
					message = new SystemMessage();
					message.project =Long.valueOf(params.Id)
					message.type = project.verified
					message.date = new Date()
					message.member =Long.valueOf(user.id)
					message.message=user?.nickname +"--申请拨款----";
					message.save(flush: true)
					//weiXinService.template_status(WeiXinConstants.service_id,donateUsersOpenid, "您好,项目《"+project.name+"》申请了拨款!请及时处理！", fmt.format(date), "申请拨款", "项目过期", "" , WeiXinConstants.server+"/project/createProjectCloseing?projectid="+project?.id)
					
					weiXinService.sendMassTemplateStatus2(WeiXinConstants.service_id, donateUsersOpenid, "您好,"+member.nickname+"的项目《"+project.name+"》申请拨款，请及时审阅！", fmt.format(date), "申请拨款", "项目过期", "成功" , WeiXinConstants.server+"/project/projectDetail?projectid="+project?.id)
					frist=1
				}
			}
			if(params.shenq=="0"){
				if(project?.apliNum<1){
					project.apliNum=1
					project.save(flush: true)
					 
					weiXinService.sendMassTemplateStatus2(WeiXinConstants.service_id, donateUsersOpenid, "您好,"+member.nickname+"的项目《"+project.name+"》申请延期，请及时审阅！", fmt.format(date), "申请延期", "项目过期", "成功" , WeiXinConstants.server+"/project/projectDetail?projectid="+project?.id)
					
					//weiXinService.template_status(WeiXinConstants.service_id,donateUsersOpenid, "您好,项目《"+project.name+"》申请了延期!请及时处理！", fmt.format(date), "申请延期", "项目过期","", WeiXinConstants.server+"/project/createProjectCloseing?projectid="+project?.id)
				   }
				 }
				
			}
			catch(Exception e){
				//println e
				LOG.error("save project 过期to 拨款  catch exception. "+e.getMessage())
			}
		withFormat {
			json {
				JSONObject json = new JSONObject()
				JSONArray projectss = new JSONArray()
				println(params.shenq);
				if(project?.apliNum>=1&&frist!=0&&params.shenq==1){
					json.put("num","1")
				}else if(params.shenq=="0"){
					json.put("num","2")
				}else{
					json.put("num","3")
				}
				projectss.add(json)
				render (projectss as JSON)
			}
		}
		
	}
	/**
	 * 项目申请拨款处理
	 * @param name,description,detail
	 * @return null
	 *
	 * **/
	def applicationfund(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def project
		def message
		def frist=0
		def member
		DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd H:mm");
		Map<String, String> donateUsersOpenid = new HashMap<String, String>()
		Date  date = new Date();
		def members = Member.findAllByPushFlag(true);
		for(Member member2:members){
			donateUsersOpenid.put(member2?.openid , member2?.nickname)
		}
		try{
				
				project = Project.findById(params.Id);
				 member =Member.findById(project.member)
				if(project.apliNum<1){
					project.apliNum=1
					project.save(flush: true)
					message = new SystemMessage();
					message.project =Long.valueOf(params.Id)
					message.type = project.verified
					message.date = new Date()
					message.member =user.id
					message.message=user?.nickname +"--申请拨款----";
					message.save(flush: true)
					frist=1
					weiXinService.sendMassTemplateStatus2(WeiXinConstants.service_id, donateUsersOpenid, "您好,"+member.nickname+"的项目《"+project.name+"》申请拨款，请及时审阅！", fmt.format(date), "申请拨款", "项目筹满", "成功" , WeiXinConstants.server+"/project/projectDetail?projectid="+project?.id)
					
					//weiXinService.template_status(WeiXinConstants.service_id,donateUsersOpenid, "您好,项目《"+project.name+"》申请了拨款!请及时处理！", fmt.format(date), "申请拨款", "项目筹满", "" , WeiXinConstants.server+"/project/createProjectCloseing?projectid="+project?.id)
				}
			}
			catch(Exception e){
				//println e
				LOG.error("save project To拨款  catch exception. "+e.getMessage())
			}
		withFormat {
			json {
				JSONObject json = new JSONObject()
				JSONArray projectss = new JSONArray()
				if(project?.apliNum>=1&&frist!=0){
					json.put("num","1")
				}else{
					json.put("num","2")
				}
				projectss.add(json)
				render (projectss as JSON)
			}
		}
	}
	
	
	/**
	 * 项目列表
	 */
	def projectListsign(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		//微信分享参数
		def url = WeiXinConstants.server + "/project/projectList"
		if(request.getQueryString()){
			url = (url + "?" + request.getQueryString())
		}
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.server+"/images/scfire.png"
		def shareUrl = WeiXinConstants.server
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "projectlistmb"
				}
				if("mobile".equals(str)){
					render view: "projectlistmb", model: [tuser:(Member)user,appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign,shareUrl:shareUrl , imgUrl : imgUrl]
				}
			}
		}
		
	}
	/**
	 * 项目搜索
	 * @param name,description,detail
	 * @return null
	 *
	 * **/
	def projectSearch(){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		params.max = 20
		String search = params.search
		String sign = params.sign
		def projects
		def Criteria = Project.createCriteria()
		MainCate mCate = null
		boolean flag=true
		if(sign!=null){
			if(sign=="000000"){
				flag=false
				def filterClosure2 = {
					or{
						eq("verified",SCFIREConstants.PROJECT_APPROVE_EXPIRED)
						eq("verified",SCFIREConstants.PROJECT_APPROVE_PASS)
						eq("verified",SCFIREConstants.PROJECT_APPROVE_EXECUTE)
						eq("verified",SCFIREConstants.PROJECT_APPROVE_OVER)
						eq("verified","doing")
					}
					order("id","desc")
				}
				projects = Criteria.list(params,filterClosure2);
			}else{
				mCate = MainCate.findByCode(sign)
			}
		}
		def filterClosure = {
			or{
				eq("verified",SCFIREConstants.PROJECT_APPROVE_EXPIRED)
				eq("verified",SCFIREConstants.PROJECT_APPROVE_PASS)
				eq("verified",SCFIREConstants.PROJECT_APPROVE_EXECUTE)
				eq("verified",SCFIREConstants.PROJECT_APPROVE_OVER)
				eq("verified","doing")
				
			  }
			and{
				or{
					eq('mainCate', mCate)
					like("name","%"+search+"%")
					like("description","%"+search+"%")
					
				}
				order("id","desc")
			}
		}
		if(flag){
			projects = Criteria.list(params,filterClosure);
		}
		
		withFormat {
			json {
				JSONArray projectss = new JSONArray()
				for(Project project :projects){
					JSONObject json = new JSONObject()
					json.put("id",project.id)
					json.put("img",project.img)
					json.put("name",project.name)
					json.put("progress",project.progress)
					json.put("verified",project.verified)
					json.put("donatenum",project.donateNum)
					DecimalFormat decimalFormat=new DecimalFormat("#0.00")
					String donatemoney = decimalFormat.format(project.realAmount)
					json.put("money",donatemoney)
					json.put("description",project.description)
					projectss.add(json)
				}
				render (projectss as JSON)
			}
		}
	}
	/**
	 * 项目分类查看
	 * @param name,description,detail
	 * @return null
	 */ 
	def projectsignJson(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		params.max = 20
		String sign = params.sign
		if(sign==null){
			sign=1;
		}
		def projects
		MainCate mCate = null
		def Criteria = Project.createCriteria()
		def filterClosure = {
			if(sign.equals("1")){
				or{
					eq("verified",SCFIREConstants.PROJECT_APPROVE_EXPIRED)
					eq("verified",SCFIREConstants.PROJECT_APPROVE_PASS)
					eq("verified",SCFIREConstants.PROJECT_APPROVE_EXECUTE)
				  }
			}
			if(sign.equals("2")){
				eq("verified","doing")
			}
			if(sign.equals("3")){
				eq("verified",SCFIREConstants.PROJECT_APPROVE_OVER)
			}
			order("id", "desc")
		}		
		projects = Criteria.list(params,filterClosure)
		withFormat {
			json {
				JSONArray projectss = new JSONArray()
				for(Project project :projects){
					JSONObject json = new JSONObject()
					json.put("id",project.id)
					json.put("img",project.img)
					json.put("name",project.name)
					json.put("progress",project.progress)
					json.put("verified",project.verified)
					json.put("donatenum",project.donateNum)
					DecimalFormat decimalFormat=new DecimalFormat("#0.00")
					String donatemoney = decimalFormat.format(project.realAmount)
					json.put("money",donatemoney)
					json.put("description",project.description)
					projectss.add(json)
				}
				render (projectss as JSON)
			}
		}
	}
	
	
	
	
	
	
	
	/**
	 * 查看企业爱心池信息展现
	 * @param null
	 * @return null
	 *
	 * **/
	def donatematchDetail(){
		try {
			
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		//def roles = springSecurityService.getAuthentication()?.authorities
		params.max = 20
		def url = WeiXinConstants.server + "/project/donatematchDetail?"+request.getQueryString()
		String fundPoolid = params.fundPoolid
		String projectid = params.projectid
		FundPool fundpool= null
		def project =Project.findById(Long.valueOf(projectid))
		fundpool = FundPool.findById(Long.valueOf(fundPoolid))
		def fRuler =FRuler.findByProject(project)
		if (fundpool == null) {
			notFound()
			return
		}
		if (fRuler.fundPool != fundpool) {
			notFound()
			return
		}
		
		def filterClosure = {
			and{
				eq("fundPool",fundpool.id)
				eq('project', project.id)
				}
			order("date","desc")
			}
		def Criteria = FDonate.createCriteria()
		def fDonates = Criteria.list(params,filterClosure)
		
		def totalCount= Criteria.count(filterClosure)
		//def totalCount = fDonatesTotal.size()
		
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm")
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "donatematchlistmb", model: [project:project,fundpool:fundpool,fRuler:fRuler,fDonates:fDonates,user:user,totalCount:totalCount,fundPoolid:fundPoolid]
				}
				if("mobile".equals(str)){
					render view: "donatematchlistmb", model: [project:project,fundpool:fundpool,fRuler:fRuler,fDonates:fDonates,user:user,totalCount:totalCount,fundPoolid:fundPoolid]
				}
			}
			json {
				JSONArray donatesjson = new JSONArray()
				for(FDonate f:fDonates){
					JSONObject json = new JSONObject()
					def member =Member.findById(f.member)
					if(member?.nickname){
						json.put("nickname", member.nickname)
					}else{
						json.put("nickname", "爱心天使")
					}
					json.put("donate_fee", f.donate_fee)
					json.put("date",sdf.format(f.date).substring(5))
					//(donate.date.getMonth()+1)+"-"+donate.date.getDate()+" "+donate.date.getHours()+":"+donate.date.getMinutes()
					donatesjson.add(json)
				}
				render donatesjson as JSON
			}
		}
		} catch (Exception e) {
		e.printStackTrace()
	}

	}
	def donatematchDetail2(){
		try {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		//def roles = springSecurityService.getAuthentication()?.authorities
		params.max = 20
		def url = WeiXinConstants.server + "/project/donatematchDetail?"+request.getQueryString()
		String fundPoolid = params.fundPoolid
		String projectid = params.projectid
		FundPool fundpool= null
		def project =Project.findById(Long.valueOf(projectid))
		fundpool = FundPool.findById(Long.valueOf(fundPoolid))
		def fRuler =FRuler.findByProject(project)
		if (fundpool == null) {
			notFound()
			return
		}
		if (fRuler.fundPool != fundpool) {
			notFound()
			return
		}
		
		def filterClosure = {
			and{
				eq("fundPool",fundpool.id)
				eq('project', project.id)
				}
			order("date","desc")
			}
		def Criteria = FDonate.createCriteria()
		def fDonates = Criteria.list(params,filterClosure)
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm")
		withFormat {
			
			json {
				JSONArray donatesjson = new JSONArray()
				for(FDonate f:fDonates){
					JSONObject json = new JSONObject()
					def member =Member.findById(f.member)
					if(member?.nickname){
						json.put("nickname", member.nickname)
					}else{
						json.put("nickname", "爱心天使")
					}
					json.put("donate_fee", f.donate_fee)
					json.put("date",sdf.format(f.date).substring(5))
					//(donate.date.getMonth()+1)+"-"+donate.date.getDate()+" "+donate.date.getHours()+":"+donate.date.getMinutes()
					donatesjson.add(json)
				}
				render donatesjson as JSON
			}
		}
		} catch (Exception e) {
		e.printStackTrace()
	}

	}
	
	
	/**
	 * 项目列表
	 * @param null
	 * @return null
	 *
	 * **/
	def projectList() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		//def roles = springSecurityService.getAuthentication()?.authorities
		params.max = 20

		//加载分类信息
		List<MainCate> mainCates = MainCate.list()
		//加载项目信息
		List<Project> projects = new LinkedList<Project>()
		List<Project> projects_tmp = null
		MainCate mCate = null
		def Criteria = Project.createCriteria()
		//排序信息
		String recommand = null
		
		def filterClosure = {
			
			or{
				and{
					eq("verified",SCFIREConstants.PROJECT_APPROVE_PASS)
					if(params.code != null){
						mCate = MainCate.findByCode(params.code)
						eq('mainCate', mCate)
					}
				}
				and{
					eq("verified",SCFIREConstants.PROJECT_APPROVE_EXECUTE)
					if(params.code != null){
						mCate = MainCate.findByCode(params.code)
						eq('mainCate', mCate)
					}
				}
				and{
					eq("verified",SCFIREConstants.PROJECT_APPROVE_EXPIRED)
					if(params.code != null){
						mCate = MainCate.findByCode(params.code)
						eq('mainCate', mCate)
					}
				}
				and{
					eq("verified",SCFIREConstants.PROJECT_APPROVE_OVER)
					if(params.code != null){
						mCate = MainCate.findByCode(params.code)
						eq('mainCate', mCate)
					}
				}
			}
			
			if(params.recommand.equals("donate")){
				order("donateNum", "desc")
				order("progress", "asc")
				recommand = SCFIREConstants.PROJECT_SORT_HOT
			}else if(params.recommand.equals("all")){
				order("progress", "asc")
				order("createDate", "desc")
				recommand = SCFIREConstants.PROJECT_SORT_NEW
			}else{
				order("createDate", "desc")
			}
			
		}
		
		projects = Criteria.list(params,filterClosure)
		//微信分享参数
		def url = WeiXinConstants.server + "/project/projectList"
		if(request.getQueryString()){
			url = (url + "?" + request.getQueryString())
		}
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.server+"/images/scfire.png"
		def shareUrl = WeiXinConstants.server
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "projectlistmb", model: [projects:projects,mainCates:mainCates,mCate:mCate,recommand:recommand]
				}
				if("mobile".equals(str)){
					render view: "projectlistmb", model: [projects:projects,mainCates:mainCates,mCate:mCate,recommand:recommand,tuser:(Member)user,
						appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign,shareUrl:shareUrl , imgUrl : imgUrl]
				}
			}
			json {
				JSONArray projectss = new JSONArray()	
				
				for(Project project :projects){
					JSONObject json = new JSONObject()
					json.put("id",project.id)
					json.put("img",project.img)
					json.put("name",project.name)
					json.put("progress",project.progress)
					json.put("verified",project.verified)
					json.put("donatenum",project.donateNum)
					DecimalFormat decimalFormat=new DecimalFormat("#0.00")
					String donatemoney = decimalFormat.format(project.realAmount)
					json.put("money",donatemoney)
					json.put("description",project.description)
					projectss.add(json)
				}
				render projectss as JSON
			}
		}
		
	}
	



	/**
	 * 项目详细信息
	 * @param project id
	 * @return null
	 *
	 * **/
	def projectDetail(){
		try {
		String projectid = params.projectid
		def url = WeiXinConstants.server + "/project/projectDetail?"+request.getQueryString()
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		/*def roles = springSecurityService.getAuthentication()?.authorities*/
		
		//项目捐赠人列表
		Set<Member> donates = new HashSet<Member>()
		Project project = null
		//一起捐和所有捐赠数（防止不必要的project中级联的donate加载）
		int donatesCount = 0;
		int subprjCount = 0;
		
		//剩余天数
		def lastDate = null
		//微信发送朋友所需要的参数
		
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.img_url
		
		def openid = user.openid
		
		JSONObject authinfo = new JSONObject();
		authinfo.put("openid", user.openid);
		authinfo.put("nickname", user?.nickname);
		authinfo.put("province", user.province);
		authinfo.put("city", user.city);
		authinfo.put("country", user.country);
		authinfo.put("headimgurl", user?.headimgurl);
		authinfo.put("unionid", user.unionid);
		authinfo.put("sex", user.sex);		
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
			
			def criteriaDonate = Donate.createCriteria()
			def CriteriaSubPrj = SubProject.createCriteria()
			
			def filterDonate ={
				eq('project', project)
				maxResults(30)
			}
			def filterDonatesCount ={
				eq('project', project)
			}
			def filterSubPrj ={
				eq('project', project)
			}
			def fDonates = criteriaDonate.list(filterDonate)
			
			
			imgUrl += project.img
			
			Date curDate = new Date()
			if(curDate>=project.endDate){
				lastDate = 0
			}else{
				lastDate = project.endDate - curDate
			}
			//捐赠人信息去重
			if(fDonates!=null){
				//最多查询前10个
				for(Donate d:fDonates){
					Member m = Member.findById(d.member)
					//donates.add(d.member)
					donates.add(m)
					if(donates.size()>10){
						break
					}
				}
			}
			def projectPics = ProjectPic.findAllByProject(project.id)
			
			def fRuler = FRuler.findByProject(project)
			def projectMember = Member.findById(project.member)
			def subProjectSize = SubProject.countByProject(Long.valueOf(projectid))
			def fundraises = Fundraise.findAllByProject(project.id)

			if(!project?.qrCode){
			
				/*
				UUID uuid = UUID.randomUUID()
				LogoCode logoCode = new LogoCode();
				String qrCode =uuid.toString()
				String imgPath = WeiXinConstants.imgDir+qrCode;
				String logoPath ="E:/scfire.png"
				String encoderContent = url;
				int i= logoCode.createQRCode(encoderContent, imgPath, logoPath, 24);
				*/
				UUID uuid = UUID.randomUUID()
				String content = WeiXinConstants.server + "/project/projectDetail?"+project.id;
				String qrCode =uuid.toString()
				String filePath = WeiXinConstants.imgDir+qrCode;
				try {		
					File file = new File(filePath);
					ZXingCode zp = new ZXingCode();
					BufferedImage bim = zp.getQR_CODEBufferedImage(content, BarcodeFormat.QR_CODE, 450, 450,
							zp.getDecodeHintType());
					ImageIO.write(bim, "jpeg", file);
					zp.addLogo_QRCode(file, new File(WeiXinConstants.imgDir+"scfire.png"), new LogoConfig(),filePath);
					project.qrCode = qrCode
					def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
					DBCollection projectCollection = db.getCollection("project")
					DBObject queryCondition= new BasicDBObject()
					queryCondition.put("_id",Integer.valueOf(projectid))
					BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("qrCode", qrCode))
                    projectCollection.update(queryCondition, updateParameter,true,true)
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "projectdetailmb", model: [fundraises:fundraises,project:project,projectPics:projectPics,lastDate:lastDate,donates:donates, appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign , url : url , name : user?.nickname , imgUrl : imgUrl, openid:openid, authinfo:authinfo,fRuler:fRuler,subProjectSize:subProjectSize,projectMember:projectMember]
				}
				if("mobile".equals(str)){
					render view: "projectdetailmb", model: [fundraises:fundraises,project:project,projectPics:projectPics,lastDate:lastDate,donates:donates, appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign , url : url , name : user?.nickname , imgUrl : imgUrl, openid:openid, authinfo:authinfo,fRuler:fRuler,subProjectSize:subProjectSize,projectMember:projectMember]
				}
			}
			json {
				render (project as JSON)
			}
		}
		} catch (Exception e) {
		e.printStackTrace()
	}
	}
	
	def projectDetailPC(){
		
		try {
		String projectid = params.projectid
		def url = WeiXinConstants.server + "/project/projectDetail?"+request.getQueryString()
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		/*def roles = springSecurityService.getAuthentication()?.authorities*/
		
		//项目捐赠人列表
		Set<Member> donates = new HashSet<Member>()
		Project project = null
		//一起捐和所有捐赠数（防止不必要的project中级联的donate加载）
		int donatesCount = 0;
		int subprjCount = 0;
		
		//剩余天数
		def lastDate = null
		//微信发送朋友所需要的参数
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
			
			def criteriaDonate = Donate.createCriteria()
			def CriteriaSubPrj = SubProject.createCriteria()
			
			def filterDonate ={
				eq('project', project)
				maxResults(30)
			}
			def filterDonatesCount ={
				eq('project', project)
			}
			def filterSubPrj ={
				eq('project', project)
			}
			def fDonates = criteriaDonate.list(filterDonate)
			Date curDate = new Date()
			if(curDate>=project.endDate){
				lastDate = 0
			}else{
				lastDate = project.endDate - curDate
			}
			//捐赠人信息去重
			if(fDonates!=null){
				//最多查询前10个
				for(Donate d:fDonates){
					Member m = Member.findById(d.member)
					//donates.add(d.member)
					donates.add(m)
					if(donates.size()>10){
						break
					}
				}
			}
			def fRuler = FRuler.findByProject(project)
			def subProjectSize = SubProject.countByProject(Long.valueOf(projectid))
			def projectmember= Member.findById(project.member)
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "projectdetail", model: [projectmember:projectmember,project:project,lastDate:lastDate,donates:donates,fRuler:fRuler,subProjectSize:subProjectSize]
				}
			}
			json {
				render (project as JSON)
			}
		}
		} catch (Exception e) {
		e.printStackTrace()
	}
	
	}
		
		
		
		
		
		
		
	
/*	*//**
	 * @创建项目结项报告（project状态为：execute或expired）
	 */
	def createProjectCloseing(){
		def url = WeiXinConstants.server + "/project/createProjectCloseing?"+request.getQueryString()
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def user = springSecurityService.getCurrentUser()
		String projectid= params.projectid;
		Member member = (Member)user
		if (params.projectid == null) {
			notFound()
			return
		}
		def project = Project.findById(Long.valueOf(params.projectid.toString()))
		if (project == null) {
			notFound()
			return
		}
		int payment=0
		def payments = Payment.findAllByProject(project.id)
		if(payments!=null){
			for(Payment p:payments){
				if(p?.payMoney){
					payment=payment+p?.payMoney
				}
			}
		}	
		if(!(project.verified=="execute" || project.verified=="expired" || project.verified=="over"|| project.verified=="doing")){
			notFound()
			return
		}
		ProjectClosing projectClosingInstance = ProjectClosing.findByProject(project.id)
		if(projectClosingInstance==null){
			projectClosingInstance = new ProjectClosing();
		}
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.img_url
		imgUrl += project.img
		def shareUrl = WeiXinConstants.server+ "/project/createProjectCloseing?projectid="+project.id
		String s
		if(projectClosingInstance?.summary){
			if(projectClosingInstance.summary.length()>=50){
				s=projectClosingInstance.summary.substring(0, 50)+"..."
			}else{
			s=projectClosingInstance.summary
			}
		}
		def member2 = Member.findById(project.member)
		withFormat {
			html {
				if("pc".equals(str)){
					
						if(projectClosingInstance?.verified=="wait" || projectClosingInstance?.verified=="pass"){
							render view: "projectclosingdetailmb", model: [projectClosing:projectClosingInstance,project:project,payment:payment,
								appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign,shareUrl:shareUrl , imgUrl : imgUrl,shareDetail:s]
						}else{
						if(member.id ==member2.id ||member.username=="admin")
						render view: "projectclosingmb", model: [projectClosing:projectClosingInstance,project:project,payment:payment]
						}
				}
				if("mobile".equals(str)){
					if(projectClosingInstance?.verified=="wait"&& member.id !=member2.id){
						notFound()
						return
					}
					if(projectClosingInstance?.verified=="wait" || projectClosingInstance?.verified=="pass"){
						render view: "projectclosingdetailmb", model: [projectClosing:projectClosingInstance,project:project,payment:payment,
							appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign,shareUrl:shareUrl , imgUrl : imgUrl,shareDetail:s]
					}else{
					if(member.id ==member2.id)
					render view: "projectclosingmb", model: [projectClosing:projectClosingInstance,project:project,payment:payment]
					}
				}
			}
			json {
			}
		}
	}
	
	 def savProjectCloseing(ProjectClosing projectClosingInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		Member member =(Member)springSecurityService.getCurrentUser()
		String projectid= params.projectid;
		if (params.projectid == null) {
			notFound()
			return
		}
		def project = Project.findById(Long.valueOf(params.projectid.toString()))
		if (project == null) {
			notFound()
			return
		}
		def projectClosing = ProjectClosing.findByProject(project.id)
		if(projectClosing!=null){
			if(projectClosing?.verified=="pass"){
				notFound()
				return
			}
		}
		try{
			if(!projectClosingInstance?.createDate){
				projectClosingInstance.createDate = new Date();
			}
			//projectClosingInstance.createDate = new Date();
			projectClosingInstance.updateDate = new Date();
			def projectMember = Member.findById(project.member)
			if(member.username=="admin"){
				projectClosingInstance.member=projectMember.id
			}else{
				projectClosingInstance.member= member.id
			}
			projectClosingInstance.project=project.id
			projectClosingInstance.verified="wait"
			projectClosingInstance.save(flush :true)
			DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd H:mm");
			Map<String, String> donateUsersOpenid2 = new HashMap<String, String>()
			def pushMembers = Member.findAllByPushFlag(true);
			for(Member member2:pushMembers){
				donateUsersOpenid2.put(member2?.openid , member2?.nickname)
			}
			//def member2 = Member.findById(project.member)
			weiXinService.sendMassTemplateStatus2(WeiXinConstants.service_id, donateUsersOpenid2, "您好,"+projectMember?.nickname+"的项目《"+project.name+"》，已经提交结项报告！", fmt.format(new Date()), "结项报告", "结项报告", "成功" , WeiXinConstants.server+"/project/createProjectCloseing?projectid="+project?.id)	
		}catch(Exception e){
			LOG.error("Save Feedback project catch exception. "+e.getMessage())
			notFound()
			return
		}
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "projectClosingsuccessmb", model: [projectClosing:projectClosingInstance,project:project]
				}
				if("mobile".equals(str)){
					render view: "projectClosingsuccessmb", model: [projectClosing:projectClosingInstance,project:project]
				}
			}
		}
	 }
	
	
	
	/**
	 *
	 * 拉取异步的项目反馈
	 * params.offset 偏移
	 * params.projectid 所属 projectid
	 * params.max 最大记录数
	 */
	def projectFeedBackList(){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def users = springSecurityService.getCurrentUser()
		Member user = (Member)users
		JSONArray feedbackjson = new JSONArray();
		int offset = 0;
		int offsets = params.offset ? params.offset.toInteger() : 0
		if(params.max == null)
		{
			params.max = 20;
		}
		def projectFeedBacks
		def projectfeedbackTotal
		
		try{
			def c = ProjectFeedback.createCriteria()
			projectFeedBacks =  c.list(max: params.max, offset: offsets){
				eq("project", Integer.parseInt(params.projectid))
				order("date", "desc")
			}
			projectfeedbackTotal = projectFeedBacks?.size()
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm")
			Iterator<ProjectFeedback> feedbacks = projectFeedBacks.iterator();
			def project = Project.findById(Integer.parseInt(params.projectid))
			while (feedbacks.hasNext()) {
				if(offset < offsets){
				   feedbacks.next();
				   offset++;
				}else if(offset>=(offsets+params.max.toInteger())){
				  break
				}else{
				  def feedback = feedbacks.next()
				  offset++; 
				  if(false!= feedback.display_flag){
					  JSONObject fjson = new JSONObject();
					  fjson.put("id", feedback.id)
					  fjson.put("projectid", project.id)
					  fjson.put("projectname", project.name)
					  fjson.put("date",(sdf.format(feedback.date).substring(5)))
					  fjson.put("text", feedback.text)
					  fjson.put("memberid", feedback.member)
					  fjson.put("img1", feedback.img1)
					  fjson.put("img2", feedback.img2)
					  fjson.put("img3", feedback.img3)
					  fjson.put("img4", feedback.img4)
					  fjson.put("img5", feedback.img5)
					  fjson.put("img6", feedback.img6)
					  fjson.put("img7", feedback.img7)
					  fjson.put("img8", feedback.img8)
					  feedbackjson.add(fjson)
				  }
				   
				}
			}
			
		}catch(Exception e){
			LOG.error("query feedback get exception."+e.getMessage())
			render "failure"
		}
		withFormat {
			html {
				if("pc".equals(str)){
					render view:"projectFeedBackListmb", model:[user:user,projectfeedbackTotal:projectfeedbackTotal,projectFeedBacks:projectFeedBacks]
				}
				if("mobile".equals(str)){
					render view:"projectFeedBackListmb", model:[user:user,projectfeedbackTotal:projectfeedbackTotal,projectFeedBacks:projectFeedBacks]
				}
			}
			json {
				if("pc".equals(str)){
					render feedbackjson as JSON
				}
				if("mobile".equals(str)){
					render feedbackjson as JSON
				}
			}
		}
	}
	
	/**
	 * 项目反馈信息编辑
	 * @param null
	 * @return null
	 *
	 * **/
	def projectFeedbackShow(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		/*def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities*/
		//获取项目详细信息
		String projectid = params.projectid
		Project project = null
		def lastDate = null
		try{
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
		}catch(Exception e){
			LOG.error("Feed back project by projectid catch exception. "+e.getMessage())
			notFound()
			return
		}
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "projectfeedbackmb", model: [project:project]
				}
				if("mobile".equals(str)){
					render view: "projectfeedbackmb", model: [project:project]
				}
			}
			json {
				
			}
		}
	}
	
	/**
	 * 项目反馈信息保存
	 * @param null
	 * @return null
	 *
	 * **/
	def projectFeedbackSave(ProjectFeedback projectFeedbackInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def user = springSecurityService.getCurrentUser()
		Member member = (Member)user
		//获取用户基本信息
		/*def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities*/
		println projectFeedbackInstance.img1
		println projectFeedbackInstance.img2
		println projectFeedbackInstance.img3
		println projectFeedbackInstance.img4
		println projectFeedbackInstance.img5
		println projectFeedbackInstance.img6
		println projectFeedbackInstance.img7
		println projectFeedbackInstance.img8
		
		try{
			//保存项目反馈信息
			projectFeedbackInstance.date = new Date();
			projectFeedbackInstance.member = member.id
			projectFeedbackInstance.clearErrors();
			projectFeedbackInstance.feedbackType="fback"
			projectFeedbackInstance.save(flush :true)
			
		}catch(Exception e){
			LOG.error("Save Feedback project catch exception. "+e.getMessage())
			notFound()
			return
		}
		
		withFormat {
			html {
				if("pc".equals(str)){
					//跳转到项目动态
					redirect (controller: "user", action: "userFeedBackDetail")
				}
				if("mobile".equals(str)){
					//跳转到项目动态
					redirect (controller: "user", action: "userFeedBackDetail")
				}
			}
			json {
				
			}
		}
	}
	
	/***********************START PROJECT后台管理***************************************************/
	/**
	 * 显示项目列表
	 * @param null
	 * @return null
	 *
	 * **/
	def index(){
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		def projects = null
		def homes = null
		Member member = (Member)user
		try{
			projects = Project.list()
			//
			homes = Home.list()
		}catch(Exception e){
			LOG.error("get projects from user catch exception. "+e.getMessage())
		}
		
		render view: "index", model: [projects:projects,user:user,roles:roles, homes:homes]
		
	}
	
	
	/**
	 * 更新项目信息
	 * @param project id
	 * @return null
	 *
	 * **/
	@Transactional
	def updateHome() {
		def gson = new Gson()
		
		if (params.pid == null) {
			notFound()
			return
		}
		if (params.position == null) {
			notFound()
			return
		}
		if (params.status == null) {
			notFound()
			return
		}
		
		def status = params.status
		def position = params.position
		def projectInstance = Project.findById(params.pid)
		//更新home
		def homepageItem = Home.findByProject(projectInstance)
		
		if(homepageItem){
			if(params.status.equals("0")){
				//移除
				homepageItem.delete flush:true
				redirect  (controller: "project", action: "index") 
				return
			}
			else if (params.status.equals("1")){
				//新增& 修改
				homepageItem.position = Integer.parseInt(position)
			}
			else{
				notFound()
				return
			}
		}
		else{
			homepageItem = new Home();
			homepageItem.project = projectInstance
			homepageItem.position = Integer.parseInt(position)
		}
		
		//更新项目信息
		homepageItem.save (flush:true)
		
		//返回首页
		redirect  (controller: "project", action: "index")
	}
	/**
	 * 显示项目信息
	 * @param projectInstance
	 * @return null
	 *
	 * **/
	def show(Project projectInstance) {
		def userAgent = request.getHeader("User-Agent")
		String str = deviceInfoService.getDeviceInfo(userAgent)
	
		if(projectInstance == null){
			notFound()
			return
		}
		
		respond projectInstance
	}
	
	
	/**
	 * 开始项目
	 * @param null
	 * @return null
	 *
	 * **/
	def start() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def gson = new Gson()
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		
		Member member = (Member)user
		
		//判断是否已经提交或者认证通过个人认证信息
		/*if(!userService(member)){
			redirect(controller:"user",action:"userAuth")
		}*/
		if(!member.verify.equals(SCFIREConstants.USER_APPROVE_WAIT) && !member.verify.equals(SCFIREConstants.USER_APPROVE_PASS)){
			redirect(controller:"user",action:"userAuth")
		 }
		
		withFormat {
			html {
				response.setContentType("text/html;charset=UTF-8")
				if("pc".equals(str)){
					redirect(controller:"project",action:"create")
				}else{
					render view:"projectclausemb"
				}
				 
			}
			json {
				gson.setResult(false)
				gson.setCode(403)
				gson.setInfo(["errortext":projectInstance.errors])
				render gson as JSON
			}
		}
		
		respond new Project(params)
		
	}
	
	/**
	 * 创建项目
	 * @param null
	 * @return null
	 *
	 * **/
	def create(Project projectInstance) {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def gson = new Gson()
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		
		Member member = (Member)user
		
		//判断是否已经提交或者认证通过个人认证信息
		if(!member.verify.equals(SCFIREConstants.USER_APPROVE_WAIT) && !member.verify.equals(SCFIREConstants.USER_APPROVE_PASS)){
			redirect(controller:"user",action:"userAuth")
		 }
		
		
		withFormat {
			html {
				response.setContentType("text/html;charset=UTF-8")
				if("pc".equals(str)){
					respond new Project(params),view:"create",model: [user:member]
				}else{
					respond new Project(params),view:"createnewmb2",model: [user:member]
				}
				 
			}
			json {
				gson.setResult(false)
				gson.setCode(403)
				gson.setInfo(["errortext":projectInstance.errors])
				render gson as JSON
			}
		}
		
		respond new Project(params)
		
	}
	
	/**
	 * 保存项目信息
	 * @param projectInstance
	 * @return null
	 *
	 * **/
	@Transactional
	def save(Project projectInstance) {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def gson = new Gson()	
		if (projectInstance == null) {
			notFound()
			return
		}	
		if (projectInstance.hasErrors()) {
			response.setContentType("text/html;charset=UTF-8")
			respond projectInstance.errors, view:'create'
			return
		}
		
		try{
			//默认当前用户就是创建者
			Member member = (Member)springSecurityService.getCurrentUser()
			projectInstance.createDate= projectInstance.createDate? projectInstance.createDate:new Date()
			projectInstance.updateDate = new Date()
			//管理员admin编辑操作不变更项目归属者
			if(member.username.equals("admin")){
				if(projectInstance.member == 0){//项目还没有归属者，说明是admin创建项目
					projectInstance.member = member.id
				}
				else{
					//不做操作
				}
			}else{
				projectInstance.member = member.id
			}
			
			//计算募集开始时间和结束时间
			if(params.datanum != null && !params.datanum.equals("")){
				projectInstance.startDate = new Date()
				Date endDate = new Date()
				Calendar calendar = new GregorianCalendar()
				calendar.setTime(endDate)
				calendar.add(calendar.DATE,Integer.valueOf(params.datanum))
				endDate=calendar.getTime()
				projectInstance.endDate = endDate
				projectInstance.donateTimelimit = Integer.valueOf(params.datanum)
			}
			
			//获取项目归属类别
			if(params.maincate != null){
				MainCate mainCate = MainCate.findByCode(params.maincate)
				projectInstance.mainCate = mainCate.id
			}else{
				projectInstance.mainCate = 1
			}
			
			//保存项目海报图片
			if(params.projectimg != null){
				//防止图片上传引入错误
				if(params.projectimg.length() > 64){
					projectInstance.img = null;
				}else{
					projectInstance.img = params.projectimg
				}
			}
			
						
			//保存项目信息
			projectInstance.save(flush:true)
			
			//保存图文信息
			if(params.projectpic!=null){
				//remove 原来的pic
				def allPic =ProjectPics.findAllByProject(projectInstance.id)
				if( null != allPic){
					for(def pic: allPic){
						pic.delete (flush : true)
					}
				}
				if(params.projectpic instanceof String){
					ProjectPic projectPic = new ProjectPic()
					//防止图片上传引入错误
					if(params.projectpic.length() > 64){
						projectPic.pic = null;
					}else{
						projectPic.pic = params.projectpic
					}
					projectPic.content = params.projectpiccontent[0].toString() ? params.projectpiccontent[0].toString():""
					projectPic.date = new Date()
					projectPic.project = projectInstance.id
					projectPic.save flush:true
				}
				else{
					for(int i=0;i<params.projectpic.size();i++){
						ProjectPic projectPic = new ProjectPic()
						//防止图片上传引入错误
						if(params.projectpic[i].length() > 64){
							projectPic.pic = null;
						}else{
							projectPic.pic = params.projectpic[i]
						}
						
						projectPic.content = params.projectpiccontent[i]? params.projectpiccontent[i]:""
						projectPic.date = new Date()
						projectPic.project = projectInstance.id
						
						//防止时间戳一致造成的图文排列不正确的问题
						sleep(100);
						projectPic.save flush:true
					}
				}
			}
			
			double sum = 0
			
			//项目状态为draft/项目状态为wait时，初始化募集清单,新增打回状态时可以修改清单
			//其它状态募集清单不作操作
			if(params.saveType.equals(SCFIREConstants.PROJECT_APPROVE_DRAFT)||params.saveType.equals(SCFIREConstants.PROJECT_APPROVE_WAIT)||params.saveType.equals(SCFIREConstants.PROJECT_APPROVE_MODIFY)){
			   
			   //保存募集清单信息
			   if(params.fundraisename != null ){
				   //清空原清单
				   def allFundraise = Fundraise.findAllByProject(projectInstance.id)
				   if( null != allFundraise){
					   for(def fund: allFundraise){
						   fund.delete (flush : true)
					   }
				   }
				   
				   if(params.fundraisename instanceof String){
					   Fundraise fundraise = new Fundraise()
					   fundraise.name = params.fundraisename
					   fundraise.price = Float.valueOf(params.fundraiseprice)
					   fundraise.count = Integer.valueOf(params.fundraisenum)
					   sum += (fundraise.price*fundraise.count)
					   fundraise.project = projectInstance.id
					   fundraise.save flush:true
					   projectInstance.amount = sum
					   projectInstance.rest   = sum
				   }
				   else{
					   for(int i=0; i < params.fundraisename.size();i++){
						   Fundraise fundraise = new Fundraise()
						   fundraise.name = params.fundraisename[i]
						   fundraise.price = Float.valueOf(params.fundraiseprice[i])
						   fundraise.count = Integer.valueOf(params.fundraisenum[i])
						   sum += (fundraise.price*fundraise.count)
						   fundraise.project = projectInstance.id
						   fundraise.save flush:true
					   }
					   //总价四舍五入
					   projectInstance.amount = (sum *1000 % 10 > 5? ( (int) (sum *100 +1))/100.0 : ((int) (sum *100))/100.0)
					   projectInstance.rest   = projectInstance.amount
					   
				   }
			   }
			   else{
				   //
			   }
			   
			}
			
			//保存草稿的特殊处理
			if(params.saveTypeo.equals(SCFIREConstants.PROJECT_APPROVE_DRAFT)){
				//projectInstance.verified = SCFIREConstants.PROJECT_APPROVE_DRAFT
				if(projectInstance?.verified==null){
					projectInstance?.verified="draft"
				}
				projectInstance.save flush : true
				redirect(action: "edit", params:[projectid: projectInstance.id])
				return
			}
			else{
				//提交后，状态显示审核中wait
				//判断是否已经有正在筹款的项目
				if(projectInstance.verified == SCFIREConstants.PROJECT_APPROVE_DRAFT||projectInstance.verified == SCFIREConstants.PROJECT_APPROVE_PASS){
					//什么都不做.
				}else{// 筹款项目数有一个上限
					def pass = Project.findAllByMemberAndVerified(member,SCFIREConstants.PROJECT_APPROVE_PASS)
					def limit =2;
					//TODO 配置 limti 的来源和保存功能。
					if(pass.size()> limit){

						projectInstance.verified = SCFIREConstants.PROJECT_APPROVE_DRAFT
						projectInstance.save flush : true
						render view: "projectsubmitNotice", model:[project:projectInstance, limit:limit]
						return
					}
				}
				if(params.saveType.equals(SCFIREConstants.PROJECT_APPROVE_DRAFT)){
					
				}
				
				if(projectInstance?.verified=="draft"){
					projectInstance?.verified="wait"
				}
				if(projectInstance?.verified==null){
					projectInstance?.verified="wait"
				}
				if(projectInstance?.verified=="modify"){
					projectInstance?.verified="wait"
				}
				projectInstance.save flush : true
				if(!projectInstance.save()){
					projectInstance.errors.allErrors.each{
						println(it)
					}
				}
				if(!projectInstance?.qrCode){
					UUID uuid = UUID.randomUUID()
					String content = WeiXinConstants.server + "/project/projectDetail?"+projectInstance.id;
					String qrCode =uuid.toString()
					String filePath = WeiXinConstants.imgDir+qrCode;
					try {
						File file = new File(filePath);
						ZXingCode zp = new ZXingCode();
						BufferedImage bim = zp.getQR_CODEBufferedImage(content, BarcodeFormat.QR_CODE, 450, 450,
								zp.getDecodeHintType());
						ImageIO.write(bim, "jpeg", file);
						zp.addLogo_QRCode(file, new File(WeiXinConstants.imgDir+"scfire.png"), new LogoConfig(),filePath);
						projectInstance.qrCode = qrCode
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				projectInstance.save flush : true
				Map<String, String> donateUsersOpenid = new HashMap<String, String>()
				Date  date = new Date();
				DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm");
				def members = Member.findAllByPushFlag(true);
				for(Member member2:members){
					println member2?.openid+"-------"+member2?.nickname
					donateUsersOpenid.put(member2?.openid , member2?.nickname)
				}
				if(projectInstance?.verified == SCFIREConstants.PROJECT_APPROVE_PASS){
					weiXinService.sendMassTemplateStatus2(WeiXinConstants.service_id, donateUsersOpenid, "您好,"+member.nickname+"修改了项目《"+projectInstance.name+"》，请及时审阅！", fmt.format(date), "修改项目", "修改项目", "成功" , WeiXinConstants.server+"/project/projectDetail?projectid="+projectInstance?.id) 
				}else{
					projectInstance.verified = SCFIREConstants.PROJECT_APPROVE_WAIT
					weiXinService.sendMassTemplateStatus2(WeiXinConstants.service_id, donateUsersOpenid, "您好,"+member.nickname+"发起了一个新项目《"+projectInstance.name+"》，请及时审阅！", fmt.format(date), "发起项目", "发起项目", "成功" , WeiXinConstants.server+"/project/projectDetail?projectid="+projectInstance?.id)
				}								
			}
			//保存系统通知消息
			SystemMessage systemMessage = new SystemMessage()
			systemMessage.message = SCFIREConstants.SYSTEM_MESSAGE_CREATE_PROJECT_FRONT+projectInstance.name+SCFIREConstants.SYSTEM_MESSAGE_CREATE_PROJECT_BACK
			systemMessage.date = new Date()
			systemMessage.member = member.id
			systemMessage.save flush:true
			
		}catch(Exception e){
			LOG.error("save project error. "+e.getMessage())
		}
		
		//PC、MOBILE、APP
		withFormat {
			html {
				
				response.setContentType("text/html;charset=UTF-8")
				if("pc".equals(str)){
					//redirect(controller:"user",action:"userCenterDetail",params:[detail: "myproject"])
					redirect action:'submitsuccessmb'
				}else{
					//redirect(controller:"user",action:"userCenterDetail",params:[detail: "myproject"])
					redirect action:'submitsuccessmb'
				}
				 
			}
			json {
			}
		}
		
	}
	
	/**
	 *
	 * 项目提交成功的中间跳转页面
	 * @return
	 */
	def submitsuccessmb(){
		render view:"submitsuccessmb", model:[]
	}
	
	/**
	 *
	 * 项目的善款接收方页面
	 * @return
	 */
	def payeemb(){
		def projectid = params.projectid
		render view:"payeemb", model:[projectid:projectid]
	}
	
	/**
	 * 编辑项目信息
	 * @param shopInstance
	 * @return null
	 *
	 * **/
	def edit() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def gson = new Gson()
		if (params.projectid == null) {
			notFound()
			return
		}
		def projectInstance = Project.findById(Long.valueOf(params.projectid))
		//计算剩余天数
		
		int dateNum = projectInstance.endDate ?(projectInstance.endDate - projectInstance.startDate):1
		//println projectInstance.endDate - projectInstance.startDate
		def projectPics =ProjectPic.findAllByProject(projectInstance.id)
		
		def fundraises= Fundraise.findAllByProject(projectInstance.id)
		def mainCate =MainCate.findById(projectInstance.mainCate)
		withFormat {
			html {
				response.setContentType("text/html;charset=UTF-8")
				if(projectInstance.projectDetail == null || projectInstance.projectDetail.equals("")){
					if(projectInstance.verified.equals(SCFIREConstants.PROJECT_APPROVE_DRAFT)||projectInstance.verified.equals(SCFIREConstants.PROJECT_APPROVE_MODIFY)){
						if("pc".equals(str)){
							render view:"edit", model:[mainCate:mainCate,projectInstance:projectInstance,dateNum:dateNum, projectPics:projectPics,fundraises:fundraises]
						}else{
						   if(projectInstance?.projectPics){
							   render view:"editnewmbd", model:[mainCate:mainCate,projectInstance:projectInstance,dateNum:dateNum, projectPics:projectPics,fundraises:fundraises]
						   }else{
						       render view:"editnewmbd2", model:[mainCate:mainCate,projectInstance:projectInstance,dateNum:dateNum,fundraises:fundraises]
						   }
						}
					}
					else{// 审核通过状态（禁止天数 和清单的修改）
						if("pc".equals(str)){
							render view:"edit", model:[projectInstance:projectInstance,dateNum:dateNum, projectPics:projectPics,fundraises:fundraises]
						}else{
								if(projectInstance?.projectPics){
									render view:"editnewmb", model:[mainCate:mainCate,projectInstance:projectInstance,dateNum:dateNum, projectPics:projectPics,fundraises:fundraises]
								}else{
									render view:"editnewmb2", model:[mainCate:mainCate,projectInstance:projectInstance,dateNum:dateNum,fundraises:fundraises]
								}
						
							
						}
					}
				}else{
					if("pc".equals(str)){
						render view:"edit", model:[projectInstance:projectInstance,dateNum:dateNum, projectPics:projectPics,fundraises:fundraises]
					}else{
						render "您不能使用手机编辑PC发布的项目"
					}
				}
			}
			json {
				gson.setResult(false)
				gson.setCode(403)
				gson.setInfo(["errortext":projectInstance.errors])
				render gson as JSON
			}
		}
	}
	
	/**
	 * 更新项目信息
	 * @param project id
	 * @return null
	 *
	 * **/
	@Transactional
	def update(Project projectInstance) {
		def gson = new Gson()
		
		if (projectInstance == null) {
			notFound()
			return
		}

		if (projectInstance.hasErrors()) {
			respond projectInstance.errors, view:'edit'
			return
		}
		
		//更新图片文件
		if(params.img.size != 0){
			def username = springSecurityService.authentication.name
			GridFS gridFS = new GridFS(mongo.getDB(grailsApplication.config.grails.mongo.databaseName))
			GridFSInputFile activeGFS = gridFS.createFile(params.img.getBytes())
			activeGFS.filename = "scfire"+"_"+username+"_"+params.img.fileItem.fileName
			activeGFS.contentType = params.pic.fileItem.contentType
			activeGFS.save()
			projectInstance.img = activeGFS.id.toString()
		}
			
		//更新项目信息
		projectInstance.save(flush:true)
		
		request.withFormat {
			form multipartForm {
				flash.message = message(code: 'default.updated.message', args: [message(code: 'project.label', default: 'Project'), projectInstance.id])
				redirect projectInstance
			}
			'*'{ respond projectInstance, [status: OK] }
		}
	}
	
	/**
	 * 删除项目信息
	 * @param null
	 * @return null
	 *
	 * **/
	@Transactional
	def delete(Project projectInstance) {
		
		//需要做一个验权 验权不通过将拒绝请求。
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		/*
		 * 需要知道用户权限，
		 *
		 * 1 admin 可以干掉所有项目
		 * 1.1 删除草稿/拒绝 状态项目不需要其他处理
		 * 1.2删除已上线项目需要进行捐赠回滚操作，或者，取消删除donate的行为
		 * 2  非admin 用户只能干掉自己的，并且处于草稿状态的项目
		 * 3 非admin 用户尝试干掉别人的项目时，拒绝删除操作
		 */
		Member member = (Member)user
		
		//println roles.toString()
		//是否admin
		if(roles.toString().contains("ROLE_ADMIN")){
			//是否草稿 / 审核状态 / 拒绝状态
			if(projectInstance.verified != "draft" && projectInstance.verified != "wait" && projectInstance.verified != "refuse"){
				notAllow()
				return
			}
		}
		else{
			//是否自己的项目
			def member2 = Member.findById(projectInstance.member)
			if (member2.id != member.id){
				notAllow()
				return
			}
			//募集/执行/超期/结束 状态不允许删除
			if(projectInstance.verified == "pass"
				|| projectInstance.verified == "execute"
				|| projectInstance.verified == "expired"
				|| projectInstance.verified == "over"){
				notAllow()
				return
			}
		}
		
		def gson = new Gson()
		
		if (projectInstance == null) {
			notFound()
			return
		}
		
		try{
			LOG.info("delete projectInstance.  delete By member id : "+member.id+" member name:"+member.username)
			projectInstance.delete flush:true
			
		}catch(Exception e){
			gson.setResult(false)
			gson.setCode(500)
			gson.setInfo(["text":e.toString()])
			LOG.error("delete projectInstance error. "+e.getMessage())
			render gson as JSON
		}
		
		//是否是自己删除操作判断
		String delopt = params.delopt
		if(delopt=="own"){
			redirect (controller:"user", action: "userMyProjectDetail")
		}else{
			redirect (controller:"manage", action: "projectApproveStatus", params: [status: "wait"])
		}
	}
	

	/**
	 * 异步的项目详情，接受异步请求
	 *
	 */
	def projectContent(){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		String projectid = params.projectid
		
		def project
		
		try{
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
			
		}catch(Exception e){
			LOG.error("Find project by projectid catch exception. "+e.getMessage())
			notFound()
			return
		}
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "projectContentmb", model: [project:project]
				}
				if("mobile".equals(str)){
					render view: "projectContentmb", model: [project:project]
				}
			}
			json {
				
			}
		}
		
	}
	
	def qrcode(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		render view:"qrcode"
	}
		
	/**
	 * 读取图片信息
	 * @param null
	 * @return null
	 *
	 * **/
	def imgRead(String img){
		if(!img)
			return
		try{
//			GridFS gridFS = new GridFS(mongo.getDB(grailsApplication.config.grails.mongo.databaseName))
//			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()
//			OutputStream page=response.getOutputStream()
//			GridFSDBFile gridFSDFile  = gridFS.find(new ObjectId(img))
//			gridFSDFile.writeTo(byteArrayOutputStream)
			OutputStream page=response.getOutputStream()
			byte [] data = FileUtil.imgRead(img)
			if(data != null){
				page.write(data)
				page.close()
			}
			
		}catch(Exception e){
			LOG.error("read image from mongodb error. "+e.getMessage())
			return null
		}
		return null
	}
		
	/**
	 * PC端保存图片信息
	 * @param null
	 * @return null
	 *
	 * **/
	def String imgSave(){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		UUID uuid = UUID.randomUUID()
		String img = null
		def file
		try{
			for (String key : params.keySet()) {
				if(key.startsWith("upload")||key.contains("fileData")){
					file = params.get(key)
				}
			}
//			def username = springSecurityService.authentication.name
//			GridFS gridFS = new GridFS(mongo.getDB(grailsApplication.config.grails.mongo.databaseName))
//			GridFSInputFile activeGFS = gridFS.createFile(file.getBytes())
//			activeGFS.filename = "scfire"+"_"+username+"_"+uuid
//			activeGFS.contentType = file.contentType
//			activeGFS.save()
//			img = activeGFS.id.toString()
			
			if(file){
				double fileSize = file.size
				fileSize = fileSize / 1024  //以k作为计算单位
				if("mobile".equals(str)){//PC上传的图片不作压缩
					if(fileSize > 200){
						img = CompressImgUtil.compressImg(file.getBytes() , uuid.toString(),960, 0.9d)
					}
					else{
						img = FileUtil.imgSave(file.getBytes() , uuid.toString())
					}
				}
				else{
					if(fileSize > 200){
						img = CompressImgUtil.compressImg(file.getBytes() , uuid.toString(),960, 0.9d)
					}
					else{
						img = FileUtil.imgSave(file.getBytes() , uuid.toString())
					}
				}
			}
		}catch(Exception e){
			LOG.error("save image into mongodb error. "+e.getMessage())
			return null
		}
		
		
//		Map result = new HashMap();
//
//		result.put("uploaded", 0)
//		result.put("fileName", img)
//		result.put("url", "/scfire/project/imgRead?img="+img)
//
//		def json = new JSONObject(result)
//
//		render json as JSON
		
		render "{\"success\":\"" + true + "\",\"file_path\":\"" + "/scfire/project/imgRead?img="+img + "\"}";
	}
	
	/**
	 * 移动端保存图片信息
	 * @param null
	 * @return null
	 *
	 * **/
	def String imgSaveMb(){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		UUID uuid = UUID.randomUUID()
		String img = null
		
		try{
			def file
			for (String key : params.keySet()) {
				if(key.contains("img")){
					file = params.get(key)
				}
			}
//			def username = springSecurityService.authentication.name
//			GridFS gridFS = new GridFS(mongo.getDB(grailsApplication.config.grails.mongo.databaseName))
//			GridFSInputFile activeGFS = gridFS.createFile(file.getBytes())
//			activeGFS.filename = "scfire"+"_"+username+"_"+uuid
//			activeGFS.contentType = file.contentType
//			activeGFS.save()
//			img = activeGFS.id.toString()
			
			if(file){
				double fileSize = file.size
				fileSize = fileSize / 1024  //以k作为计算单位
				if("mobile".equals(str)){//PC上传的图片不作压缩
					if(fileSize > 200){
						img = CompressImgUtil.compressImg(file.getBytes() , uuid.toString(),960, 1.0d)
					}else{
						img = FileUtil.imgSave(file.getBytes() , uuid.toString())
					}
				}
				else{
					img = FileUtil.imgSave(file.getBytes() , uuid.toString())
				}
			}
		}catch(Exception e){
			LOG.error("savemb image into mongodb error. "+e.getMessage())
			return null
		}
		
		render img
	}
	
	/**
	 * 移动端保存图片信息
	 * @param null
	 * @return null
	 *
	 * **/
	def String imgSaveMb2(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		UUID uuid = UUID.randomUUID()
		String img = null
		
		try{
			def file=params.wangEditorMobileFile
			
			if(file){
				double fileSize = file.size
				fileSize = fileSize / 1024  //以k作为计算单位
				if("mobile".equals(str)){//PC上传的图片不作压缩
					if(fileSize > 100){
						img = CompressImgUtil.compressImg(file.getBytes() , uuid.toString(),960, 1.0d)
					}else{
						img = FileUtil.imgSave(file.getBytes() , uuid.toString())
					}
				}
				else{
					img = FileUtil.imgSave(file.getBytes() , uuid.toString())
				}
			}
		}catch(Exception e){
			LOG.error("savemb image into mongodb error. "+e.getMessage())
			return null
		}
		
		render img
	}
	
	/***********************END PROJECT后台管理***************************************************/
	/**
	 * 项目信息未找到
	 * @param null
	 * @return null
	 *
	 * **/
	protected void notFound() {
		def gson = new Gson()
		withFormat {
			html {
				flash.message = "未找到该项目！"
				redirect (controller: "errors", action: "notFound")
			}
			json {
				gson.setResult(false)
				gson.setCode(404)
				gson.setInfo(["text": "未找到该项目！"])
				render gson as JSON
			}
		}
	}
	
	/**
	 * 非法操作
	 * @param null
	 * @return null
	 *
	 * **/
	protected void notAllow() {
		def gson = new Gson()
		withFormat {
			html {
				flash.message = "操作不合法"
				redirect (controller: "errors", action: "requestForbidden")
			}
			json {
				gson.setResult(false)
				gson.setCode(404)
				gson.setInfo(["text": "操作不合法！"])
				render gson as JSON
			}
		}
	}
	
	/************************************************************************
	 *
	 * PC端后台管理页面
	 *
	 * ************************************************************************/
	
	/**
	 * 用户项目系统消息通知
	 * @param null
	 * @return null
	 *
	 * **/
	def projectSystemInfo(){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		def systemMessages = null
		int count = 0
		try{
			Member member = (Member)user
			systemMessages = member.systemMessages
			count = systemMessages.size()
		}catch(Exception e){
			LOG.error("get user system info catch exception. "+e.getMessage())
		}
		
		render view: "projectsysinfo", model: [user:user,roles:roles,systemMessages:systemMessages,count:count]
		
	}
	
	
}
